<template>
  <div class="order-confirm page">
    <van-nav-bar title="确认订单" left-arrow @click-left="$router.go(-1)" class="bg_white" />
    <div class="content" ref="webview">
      <div class="address-box " @click="goAddress">
        <img class="icon " src="/static/img/icon-order-address.png ">
        <div class="detail">
          <template v-if="address">
            <div class="name-phone ">{{address.name}} {{address.mobile | phoneFilter}}（收）</div>
            <div class="address ">{{address.prov_name}}{{address.city_name}}{{address.area_name}} {{address && address.address}}</div>
          </template>
          <template v-else>
            请添加收货地址
          </template>
        </div>
        <div class="next "></div>
      </div>
      <template v-for="(item,index) in shopList">
        <div class="order-box" :key="index">
          <div class="stroe">
            <span class="name">{{item.shop_name}}</span>
          </div>
          <div class="order-info" v-for="(data,_index) in item.cartList" :key="_index">
            <div class="imgPath">
              <van-image :width="$tools.toPX(150) " :height="$tools.toPX(150)" fit="contain " lazy-load :src="data.goods_img ">
                <template v-slot:loading>
                  <van-loading type="spinner " size="24 " />
                </template>
              </van-image>
            </div>
            <div class="detail">
              <div class="name-text">
                <div class="name van-multi-ellipsis--l2">{{data.goods_name}}</div>
                <div class="price">
                  <span class="m-price">{{data.spec_price}}</span>
                </div>
              </div>
              <div class="spec-num">
                <span>{{data.specItemList | formatSpec}}</span>
                <span>x{{data.num}}</span>
              </div>
            </div>
          </div>
          <div class="preferential">
            <div class="freight">
              <span class="label">运费</span>
              <div class="info">普通配送</div>
              <div class="price">
                <span class="m-price">{{item.shopFreight}}</span>
              </div>
            </div>
          </div>
          <div class="remark">
            <van-field v-model="item.remark" label="订单留言" rows="1" autosize type="textarea" placeholder="选填，建议留言前先与卖家沟通确认" />
          </div>
        </div>
      </template>
      <div class="payaway-box">
        <div class="away-list" @click="getShopCoupon">
          <div class="away-item">
            <span class="balance">优惠劵</span>
            <div class="amount fontSize isArrow">
              <template v-if="couponValue">
                优惠{{couponValue}}
              </template>
            </div>
          </div>
        </div>
      </div>
      <div class="payaway-box">
        <div class="away-list">
          <div class="away-item" v-if="couponValue">
            <span class="balance">优惠劵</span>
            <div class="amount">
              <span class="m-price">{{couponValue}}</span>
            </div>
          </div>
          <div class="away-item">
            <span class="balance">运费</span>
            <div class="amount">
              <span class="m-price">{{totalFreight}}</span>
            </div>
          </div>
          <div class="away-item">
            <span class="balance">商品金额</span>
            <div class="amount">
              <span class="m-price">{{totalGoodsMoney}}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="bt-box">
      <div class="info">
        <span>共{{goodsNum}}件，</span>
        <span>合计：</span>
        <span class="m-price">{{totalMoney}}</span>
      </div>
      <div class="operate" @click="exchange">
        <van-loading color="#fff " size="24" v-if="isLoading " />
        <span v-else>提交订单</span>
      </div>
    </div>
    <van-popup v-model="isPopupPay" @click-overlay="closePayPopup" round position="bottom" style="overflow-y: unset;">
      <pay-mod v-model="isPayLoading" @change="changeOrderPay" />
    </van-popup>
    <van-popup v-model="isPopupCoupon" position="bottom" style="height:100%">
      <shop-coupon v-model="isPopupCoupon" @change="onCoupon" />
    </van-popup>
  </div>
</template>
<script>
import { mapGetters } from 'vuex';
export default {
  name: 'orderConfirm',
  data () {
    return {
      isPopupCoupon: false,
      value: 1,
      couponId: 0,
      couponValue: 0,
      totalFreight: 0,
      shopCouponList: [],
      remark: '',
      isPayLoading: false,
      isLoading: false,
      totalGoodsMoney: 0,
      goodsNum: 0,
      type: '1',
      isPopupPay: false,
      goods: {},
      address: {},
      shopId: null,
      orderNo: null,
      goodsInfo: {},
      remarksText: '',
      shopList: []
    };
  },
  inject: ['isApp'],
  computed: {
    ...mapGetters(['userInfo', 'isPayPassword']),
    // 实际支付金额
    totalMoney () {
      return this.totalGoodsMoney + this.totalFreight - this.couponValue;
    }
  },
  created () {
    this.goodsSubmit();
    this.$BUS.$on('password:pay', this.withdrawSecond);
  },
  mounted () {
    const query = this.$route.query;
    if (query && query.type) {
      this.$set(this, 'type', query.type);
    }
  },
  destroyed () {
    this.$BUS.$off('password:pay');
    sessionStorage.removeItem('address');
  },
  methods: {
    // 去支付
    changeOrderPay (type) {
      this.OrderPay(type);
    },
    goodsSubmit () {
      var optins = {
      };
      if (this.$route.query.sid) {
        optins.sid = this.$route.query.sid;
      }
      if (this.$route.query.num) {
        optins.num = this.$route.query.num;
      }
      if (this.$route.query.ids) {
        optins.ids = this.$route.query.ids;
      }
      this.$API.order.init(optins).then(res => {
        if (res && !res.code) {
          this.shopList = res.data.shopList;
          this.goodsNum = res.data.goodsNum;
          this.totalFreight = res.data.totalFreight;
          this.address = JSON.parse(sessionStorage.getItem('address')) || res.data.addr;
          this.totalGoodsMoney = res.data.totalGoodsMoney;
          // this.getCoupon();
        }
      });
    },
    goDetailsLink (id) {
      this.$router.push({ path: '/order/details', query: { id: id } });
    },
    getGoodsConfirm () {

    },
    closePayPopup () {
      // this.isLoading = false;
      this.isPopupPay = false;
      // // this.$toast('你有一笔订单还未支付');
      // setTimeout(() => {
      //   this.$router.push({ path: '/order/list' });
      // }, 300);
    },
    // 获取订单留言数据
    getRemarks () {
      var str = '';
      this.shopList.map((item) => {
        str += item.remark + ',';
      });
      return str.substring(0, str.length - 1);
    },
    // 提交订单
    exchange () {
      if (!this.address && this.goodsInfo && this.goodsInfo.goods && !this.goodsInfo.goods.is_virtual) {
        this.$toast('请先添加收货地址');
        return;
      }
      var sid = this.$route.query.sid;
      var num = this.$route.query.num;
      var ids = this.$route.query.ids;
      var options = {
        remarks: this.getRemarks(),
        payPrice: this.totalMoney,
        // 订单来源（0：PC 1：手机网站 2：微信网页 3：安卓APP 4：苹果APP）
        orderSrc: this.isApp && this.$tools.device.addriod ? '3' : this.isApp && this.$tools.device.ios ? '4' : this.$tools.device.isWeiXin() ? '2' : this.$tools.device.pc ? '0' : '1'
      };
      if (this.address && this.address.id) {
        options.addrId = this.address.id;
      }
      if (this.couponId) {
        options.couponId = this.couponId;
      }
      if (this.couponValue) {
        options.couponPrice = parseFloat(this.couponValue);
      }
      if (sid) {
        options.sid = sid;
      }
      if (num) {
        options.num = num;
      }
      if (ids) {
        options.ids = ids;
      }
      this.isLoading = true;
      this.$API.order.submit(options).then(res => {
        if (!res.code) {
          this.isPopupPay = true;
          this.orderNo = res.data;
        }
        this.isLoading = false;
      });
    },
    // 拉起支付APP
    OrderPay (payMethod) {
      this.isPayLoading = true;
      var options = {
        orderNo: this.orderNo,
        payMethod
      };
      this.$API.order.pay(options).then(res => {
        if (!res.code) {
          if (window.api) {
            this.getOrder(res.data);
          } else {
            this.$toast('仅支持APP内支付');
            this.isLoading = false;
            this.isPayLoading = false;
          }
        } else {
          this.$toast('支付失败');
          this.isLoading = false;
          this.isPayLoading = false;
        }
      });
    },
    getOrder (data) {
      var wxPay = window.api.require('wxPayPlus');
      wxPay.payOrder({
        apiKey: data.appId,
        orderId: data.prepayId,
        mchId: data.mchId || '1533095261',
        nonceStr: data.nonceStr,
        timeStamp: data.timeStamp,
        package: data.packageValue,
        sign: data.sign
      }, (ret, err) => {
        if (ret.status) {
          this.$router.push({ 'path': '/prompt', query: { type: '3' } });
          this.isLoading = false;
          this.isPayLoading = false;
          // 支付成功
        } else {
          if (err.code === -2) {
            this.$toast('用户取消');
          } else if (err.code === -1) {
            this.$toast('支付失败');
          } else if (err.code === 1) {
            this.$toast('apiKey值非法');
          }
          this.isLoading = false;
          this.isPayLoading = false;
        }
      });
    },
    // 地址
    goAddress () {
      this.$router.push({ 'path': '/address/list', query: { type: 'order' } });
    },
    // 获取店铺优惠劵
    getShopCoupon (id) {
      this.isPopupCoupon = true;
    },
    // 使用优惠劵
    onCoupon (data) {
      this.couponId = data.id;
      this.getCoupon(data.id);
    },
    // 计算订单优惠劵
    getCoupon (id) {
      var sid = this.$route.query.sid;
      var num = this.$route.query.num;
      var ids = this.$route.query.ids;
      var options = {
        cid: id
      };
      if (sid) {
        options.sid = sid;
      }
      if (num) {
        options.num = num;
      }
      if (ids) {
        options.ids = ids;
      }
      this.$API.order.coupon(options).then(res => {
        if (!res.code) {
          this.couponValue = res.data;
          this.isPopupCoupon = false;
        }
      });
    }
  }
};
</script>
<style lang="less" scoped>
.order-confirm {
  display: flex;
  flex-direction: column;
  .content {
    padding: 30px 0;
    flex: 1;
    overflow: auto;
    .address-box {
      background-color: #fff;
      border-radius: 15px;
      margin: 0 25px;
      display: flex;
      margin-bottom: 25px;
      padding: 33px 22px;
      align-items: center;
      position: relative;
      .icon {
        width: 70px;
        height: auto;
      }
      .detail {
        margin: 0 23px;
        font-size: 28px;
        .name-phone {
          font-size: 34px;
          font-family: PingFang SC;
          font-weight: 800;
          color: #353535;
          line-height: 52x;
        }
        .address {
          font-size: 28px;
          font-family: PingFang SC;
          font-weight: 400;
          color: #353535;
          line-height: 36x;
          margin-top: 13px;
        }
      }
      .next {
        display: inline-block;
        width: 16px;
        height: 30px;
        position: absolute;
        right: 40px;
        background-image: url('/static/images/icon-arrow-right.png');
        background-position: center center;
        background-repeat: no-repeat;
        background-size: 16px 30px;
      }
    }
    .order-box {
      background-color: #fff;
      padding: 30px 20px 20px;
      margin: 0 25px 22px;
      border-radius: 15px;
      .inventory {
        display: flex;
        margin-top: 40px;
        justify-content: space-between;
        .item-title {
          font-size: 28px;
          line-height: 62px;
        }
      }
      .stroe {
        display: flex;
        padding-bottom: 20px;
        .name {
          margin-left: 20px;
          font-size: 28px;
          color: #353535;
          display: flex;
          align-items: center;
          &::before {
            content: '';
            display: inline-block;
            width: 26px;
            height: 26px;
            margin-right: 10px;
            margin-top: -2px;
            background-image: url('/static/img/icon-go-store.png');
            background-position: center center;
            background-repeat: no-repeat;
            background-size: contain;
          }
        }
      }
      .preferential {
        margin-top: 16px;
        .shop,
        .freight {
          display: flex;
          padding: 18px 0;
          .label {
            width: 160px;
            text-align: right;
            padding-right: 22px;
            font-size: 28px;
            color: #353535;
          }
          .info {
            font-size: 28px;
            color: #969aa6;
            flex: 1;
          }
          .price {
            color: #ff0034;
            display: flex;
            align-items: center;
            .m-price {
              font-size: 28px;
            }
          }
          .price.isArrow {
            &::after {
              content: '';
              display: inline-block;
              width: 12px;
              height: 22px;
              background-image: url('/static/images/icon-arrow-right.png');
              background-position: center center;
              background-repeat: no-repeat;
              background-size: 12px 22px;
              vertical-align: middle;
              margin-left: 32px;
            }
          }
        }
      }
      .order-info {
        display: flex;
        background-color: #fff;
        border-radius: 15px;
        padding: 15px 0 10px;
        .imgPath {
          .van-image__img {
            border-radius: 10px;
          }
        }
        .detail {
          margin-left: 30px;
          overflow: hidden;
          flex: 1;
          display: flex;
          flex-direction: column;
          .name-text {
            display: flex;
            .m-price {
              color: #ff0034;
              font-size: 32px;
              display: flex;
              justify-content: flex-start;
            }
          }
          .name {
            font-size: 30px;
            color: #353535;
            line-height: 40px;
            padding: 0 20px;
          }
          .spec-num {
            display: flex;
            justify-content: space-between;
            font-size: 24px;
            color: #999;
            line-height: 30px;
            padding: 16px 6px 5px 20px;
            flex: 1;
          }
        }
      }
      .remark {
        /deep/ .van-cell {
          padding: 25px 0;
          .van-field__label {
            width: 160px;
            text-align: right;
            padding-right: 20px;
          }
          .van-field__control {
            color: #666;
          }
        }
      }
    }
    .payaway-box {
      background-color: #fff;
      border-radius: 15px;
      padding: 0 30px;
      margin: 25px 25px;
      .title {
        font-size: 34px;
        font-family: PingFang SC;
        font-weight: 800;
        color: #353535;
        line-height: 52px;
        padding-bottom: 30px;
        border-bottom: 1px solid #eeeeee;
        .tip {
          margin-left: 21px;
          font-size: 24px;
          font-family: PingFang SC;
          font-weight: 500;
          color: #999999;
          line-height: 48px;
        }
      }
      .away-list {
        padding: 10px 0;
        .away-item {
          height: 83px;
          display: flex;
          justify-content: space-between;
          align-items: center;
          .balance {
            flex: 1;
            font-size: 30px;
            font-family: PingFang SC;
            font-weight: 500;
            color: #353535;
            line-height: 48px;
          }
          .amount {
            font-size: 32px;
            font-family: PingFang SC;
            color: #ff0034;
            line-height: 48px;
            display: flex;
            align-items: center;
          }
          .amount.fontSize {
            font-size: 28px;
            color: #969aa6;
          }
          .amount.isArrow {
            &::after {
              content: '';
              display: inline-block;
              width: 12px;
              height: 22px;
              background-image: url('/static/images/icon-arrow-right.png');
              background-position: center center;
              background-repeat: no-repeat;
              background-size: 12px 22px;
              vertical-align: middle;
              margin-left: 18px;
            }
          }
          img {
            width: 70px;
            height: 70px;
            margin-left: 35px;
          }
        }
      }
    }
  }
  .bt-box {
    height: 102px;
    background-color: #fff;
    display: flex;
    justify-content: flex-end;
    padding-left: 32px;
    align-items: center;
    padding-right: 20px;
    .info {
      font-size: 28px;
      font-family: PingFang SC;
      font-weight: 500;
      line-height: 99px;
      span:nth-child(1) {
        color: #999999;
      }
      span:nth-child(2) {
        color: #353535;
      }
      span:nth-child(3) {
        font-size: 34px;
        color: #ff0034;
        // &::before {
        //   margin-top: 8px;
        // }
      }
    }
    .operate {
      width: 220px;
      background-color: #ff0034;
      font-size: 32px;
      font-family: PingFang SC;
      color: #fff;
      height: 80px;
      line-height: 82px;
      border-radius: 80px;
      text-align: center;
      margin-left: 40px;
    }
  }
}
</style>
